package frobagroup.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Tinsley on 2016/9/20.
 */
public class ImageCut {



    public static Map abscut(MultipartFile srcImageFile, int destX, int destY, int destW, int destH) {
        Map params = new HashMap();
        try {
            String filename = srcImageFile.getOriginalFilename();
            String format = filename.substring(filename.lastIndexOf(".")+1);
            BufferedImage bi = ImageIO.read(srcImageFile.getInputStream());
            int srcWidth = bi.getWidth();
            int srcHeight = bi.getHeight();
            if (Boolean.logicalAnd(srcWidth >= destW,srcHeight >= destH)) {
                ImageFilter cropFilter = new CropImageFilter(destX, destY, destW, destH);
                Image thumbnail = Toolkit.getDefaultToolkit().createImage(
                        new FilteredImageSource(bi.getScaledInstance(srcWidth, srcHeight,Image.SCALE_DEFAULT).getSource(),
                                cropFilter));
                BufferedImage tagImage = new BufferedImage(destW, destH,BufferedImage.TYPE_INT_RGB);
                Graphics g = tagImage.getGraphics();
                g.drawImage(thumbnail, 0, 0, null);
                ByteArrayOutputStream bs = new ByteArrayOutputStream();
                ImageOutputStream ios = ImageIO.createImageOutputStream(bs);
                ImageIO.write(tagImage,format,ios);
                InputStream is = new ByteArrayInputStream(bs.toByteArray());
                g.dispose();
                params.put("is",is);
                params.putIfAbsent("size",bs.size());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return params;
    }
}
